package p2p.tracker.client;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class ClientGraph {

	private String name;

	private Map<Client, Set<Client>> graph;

	public ClientGraph(String name) {

		this.name = name;
		this.graph = new HashMap<Client, Set<Client>>();

	}

	public synchronized void addEdge(Client a, Client b) {

		if (this.graph.containsKey(a)) {

			this.graph.get(a).add(b);

		} else {

			Set<Client> a_neighbors = new HashSet<Client>();

			a_neighbors.add(b);

			this.graph.put(a, a_neighbors);

		}

		Set<Client> b_neighbors = new HashSet<Client>();

		b_neighbors.add(a);

		this.graph.put(b, b_neighbors);

	}

	public synchronized void removeEdge(Client a) {

		Set<Client> a_neighbors = this.graph.get(a);

		for (Client c : a_neighbors) {

			Set<Client> c_neighbors = this.graph.get(c);

			if (c_neighbors != null) {

				c_neighbors.addAll(a_neighbors);

				this.graph.put(c, c_neighbors);
			}

		}

		this.graph.remove(a);

	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}
